var controller = "core/control.php";

$(document).ready(function() {

	 $.ajax({
	   async: "false",
	   type: "POST",
	   url: controller,
	   data: "id=info_calendar",
	   success: function(data, textStatus) {
			tmpl = "<div class='week'><table><tr><td width='250'><span id='title' class='title'></span><span id='date' class='date'></span><br/><span id='event' class='event'></span></td><td width='50'><div id='statusbox' class='statusbox'></div><span id='notcoming' class='notcoming'></span></td><td width='300'><ul id='unavailable' class='unavailable'></ul></td><td><img id='chart' alt='chart'/></td></tr></table></div>";

			for(i=0; i<data.length; i++)
			{
				notcoming = data[i].unavailability.length;
				total = data[i].total;
				status = Math.ceil((notcoming / total) * 5);
				no = notcoming;
				yes = total - notcoming;

				$(tmpl)
					.find("#title").text("Week " + (i + 1) + ": ").removeAttr("id").end()
					.find("#date").text(data[i].date).removeAttr("id").end()
					.find("#event").text(data[i].event).removeAttr("id").end()
					.find("#statusbox").addClass("status" + status).removeAttr("id").end()
					.find("#notcoming").text(notcoming + " of " + total).removeAttr("id").end()
					.find("#chart").attr("src", "core/chart.php?yes=" + yes + "&no=" + no).end()
					.attr("id", "week" + (i+1)).appendTo("body");

				jQuery.each(data[i].unavailability, function() {
					if(parseInt(this.priority) == 1)
					{
						$("<li></li>").append($("<b></b>").text(this.person))
						.appendTo("#week" + (i+1) + " #unavailable");
					}
					else
					{
						$("<li></li>").text(this.person)
						.appendTo("#week" + (i+1) + " #unavailable");
					}
				});

				$("#week" + (i+1) + " #unavailable").removeAttr("id");
			}

			$(".week .unavailable").each(function(i) {
				more = $(this).find("li").size() > 3 ? true : false;

				$(this).find("li").each(function (i) {
					if(i == 2 && more)
					{
						$(this).after("<li class='more'>full list...</li>");
					}

					if(i > 2)
					{
						$(this).hide();
					}
				});
			});

			$(".week .unavailable").toggle(
				function () {
					$(this).find("li").each(function (i) {
						if(i == 3)
						{
							$(this).remove();
						}
						else
						{
							$(this).show();
						}
					});

					if($(this).find("li").size() > 3)
					{
						$(this).append("<li class='less'>short list...</li>");
					}
				},
				function () {
					more = $(this).find("li").size() > 3 ? true : false;

					$(this).find("li").each(function (i) {
						if(i == 2 && more)
						{
							$(this).after("<li class='more'>full list...</li>");
						}

						if(i > 2)
						{
							$(this).hide();
						}
					});

					$(this).find("li:contains(short list)").remove();
				}
			);
	   },
	   dataType: "json"
	 });

}); // ready function